<template>
  <div class="flex flex-col h-full">
    <div class="flex-grow overflow-hidden flex cate-left">
      <div class="w-[286px] h-full bg-white mr-4">
        <div :class="TITLE_CLASS">
          <div class="flex items-center w-full">
            <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
            <div class="text-[#242930] text-sm ml-[10px]">分类列表</div>
            <!--            <el-button-->
            <!--              type="danger"-->
            <!--              size="small"-->
            <!--              plain-->
            <!--              class="ml-auto"-->
            <!--              :disabled="!checkList.length"-->
            <!--              @click="delCate"-->
            <!--              >删除</el-button-->
            <!--            >-->
          </div>
        </div>
        <div class="px-[20px] py-[16px] h-[calc(100%_-_54px)]">
          <el-input
            v-model="category"
            :prefix-icon="useRenderIcon('iconamoon:search-light')"
          />
          <el-scrollbar class="mt-4 scroll-height">
            <el-checkbox-group v-model="checkList">
              <div
                v-for="(item, index) in categoryList"
                :key="item.id"
                :class="[
                  'striped cate flex items-center pr-2',
                  categoryChoose.id === item.id ? 'active' : ''
                ]"
                @click="cateClick(item)"
              >
                <!--                <el-checkbox :value="item.id" />-->
                <div>{{ index + 1 }}、{{ item.name }}</div>
                <!--                <i class="hover:text-[#3176BC] ml-auto">-->
                <!--                  <IconifyIconOnline icon="ep:edit-pen" />-->
                <!--                </i>-->
              </div>
            </el-checkbox-group>
          </el-scrollbar>
          <!--          <el-button-->
          <!--            class="w-full !h-[46px] !text-[&#45;&#45;el-color-primary] font-[500] !text-[14px] disabled:!text-[&#45;&#45;autata-font-gray-color]"-->
          <!--            color="#F5F9FF"-->
          <!--            size="small"-->
          <!--            @click="addCate"-->
          <!--            >添加分类</el-button-->
          <!--          >-->
        </div>
      </div>

      <div class="w-full h-full bg-white">
        <div :class="TITLE_CLASS">
          <div class="flex items-center">
            <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
            <div class="text-[#242930] text-sm ml-[10px]">物料列表</div>
          </div>

          <div class="w-2/3 min-w-[420px]">
            <AuForm
              ref="formRef"
              class="mat-btn"
              :formList="formList"
              @submit="search"
            />
          </div>
        </div>
        <div class="h-[calc(100%_-_55px)]">
          <AuTable
            ref="tableRef"
            v-bind="gridOption"
            @actionClick="actionClick"
          >
            <template #expiry_default="{ row }">
              <el-tag :type="row.expiryId ? 'primary' : 'info'"
                >{{ row.expiryId ? "已激活" : "未激活" }}
              </el-tag>
            </template>
            <template #status_default="{ row }">
              <el-tag :type="row.publish_status === 1 ? 'success' : 'info'"
                >{{ row.publish_status === 1 ? "上架" : "下架" }}
              </el-tag>
            </template>
          </AuTable>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { AuTable } from "@/components/AuTable";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";
import { isArray, useGlobal } from "@pureadmin/utils";
import { BaseProps } from "@/components/AuForm/type";
import {
  CategoryProp,
  expiryGetList,
  ExpiryListProp,
  getCategory,
  getMaterialDetList,
  MaterialDetailProp
} from "@/api/expiry/expiry";
import { AuForm } from "@/components/AuForm";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useRouter } from "vue-router";
import { cloneDeep } from "lodash-unified";
import { STORAGE_LIST } from "@/views/expiry/material/materialManage/constants";
import { isNumber } from "@/store/utils";
import { formulaVerGetList, getFormulaList } from "@/api/teaInfuser/formula";

defineOptions({
  name: "materialList"
});

// region 声明ref变量集合
const TITLE_CLASS =
  "flex items-center justify-between h-[54px] border-b border-[--autata-border-color] px-[16px]";
const { $storage } = useGlobal<GlobalPropertiesApi>();
const { proxy } = getCurrentInstance();
const router = useRouter();

const category = ref("");
const categoryList = ref([]);
const checkList = ref<number[]>([]);
const categoryChoose = ref<Partial<CategoryProp>>({
  name: ""
});

let tableDataSource = [];

const formList = ref<BaseProps[]>([
  {
    type: "select",
    key: "expiryStatus",
    label: "效期状态",
    placeholder: "请选择效期状态",
    valueKey: "value",
    labelKey: "label",
    span: 8,
    emptyValues: [null, undefined],
    defaultValue: "",
    style: { width: "100%" },
    options: [
      {
        value: "",
        label: "全部"
      },
      {
        value: 0,
        label: "未激活"
      },
      {
        value: 1,
        label: "已激活"
      }
    ]
  },
  {
    type: "input",
    label: "物料名称",
    key: "name",
    span: 8,
    placeholder: "请输入物料名称"
  }
]);
const gridOption = reactive<PropDefines>({
  isServerPage: true,
  columns: [
    { field: "matId", title: "物料ID" },
    { field: "name", title: "名称" },
    // {
    //   field: "expiryStatus",
    //   title: "效期状态",
    //   slots: { default: "expiry_default" }
    // },
    {
      field: "publish_status",
      title: "状态",
      align: "center",
      slots: { default: "status_default" }
    },
    // {
    //   field: "expiryTime",
    //   title: "效期",
    //   align: "center",
    //   formatter: ({ cellValue }) => {
    //     const val = isNumber(cellValue) ? (cellValue / 3600).toFixed(2) : 0;
    //     return `${val ?? 0}小时`;
    //   }
    // },
    // {
    //   field: "storageMethod",
    //   title: "存储方式",
    //   align: "center",
    //   formatter: ({ cellValue }) => {
    //     if (cellValue) {
    //       return STORAGE_LIST.find(v => v.value == cellValue)?.label;
    //     }
    //   }
    // },
    { field: "note", title: "备注" }
  ],
  actions: [],
  topTools: [],
  dataSource: []
});

const formRef = ref();
const tableRef = ref();
// endregion

// region 公共方法的集合
async function getFormula() {
  const { data: versionList } = await formulaVerGetList({
    start_page: 0,
    size: 0
  });
  const allFormulaList = [];
  if (isArray(versionList) && versionList.length > 0) {
    const twoData = versionList; // .splice(0, 2);
    for (const item of twoData) {
      const { data: formulaList } = await getFormulaList({
        start_page: 0,
        size: 0,
        hxtFormula: {
          version: item.id,
          ...formRef.value.getFormData()
        }
      });
      for (const formulaItem of formulaList) {
        allFormulaList.push({
          id: formulaItem.id,
          matId: formulaItem.formulaSubid,
          material_id: formulaItem.formulaId,
          note: formulaItem.note,
          name: formulaItem.name,
          publish_status: formulaItem.publishStatus,
          materialSource: "泡茶机",
          type_id: 999919999,
          type_name: "成品茶"
        });
      }
    }
  }
  return allFormulaList;
}

async function handleMatExpiry(): Promise<{
  [key: string]: ExpiryListProp[];
}> {
  const matIdList = {};
  const res = await expiryGetList({});
  if (!isArray(res.data)) return matIdList;
  for (const item of res.data) {
    if (!matIdList[item.materialId]) {
      matIdList[item.materialId] = [];
    }
    matIdList[item.materialId].push(item);
  }
  return matIdList;
}

function handleMatWithExpiry(
  matIdList: { [key: string]: ExpiryListProp[] },
  materialData: MaterialDetailProp[]
): (MaterialDetailProp & ExpiryListProp)[] {
  return materialData.map(item => {
    if (matIdList[item.material_id]) {
      const expiryList = matIdList[item.material_id];
      const expiry = expiryList[0];
      expiry.expiryId = expiry.id;
      return { ...expiry, ...item };
    } else {
      return item;
    }
  }) as (MaterialDetailProp & ExpiryListProp)[];
}

async function getMatData() {
  const resExpiry = await handleMatExpiry();
  getMaterialDetList(formRef.value.getFormData()).then(async res => {
    const matList = res.data.map(v => {
      return {
        ...v,
        matId: v.material_id,
        materialSource: "柜式机"
      };
    });
    // const formulaList = await getFormula();
    tableDataSource = [...matList];
    // tableDataSource = handleMatWithExpiry(resExpiry, cloneDeep(concatList));
    cateClick(categoryChoose.value as CategoryProp);
  });
}

function init() {
  getCategory().then(async res => {
    categoryList.value = res.data;
    categoryList.value.unshift({
      name: "全部",
      id: 0
    });
    // categoryList.value.push({
    //   name: "成品茶",
    //   id: 999919999
    // });
    categoryChoose.value = res.data[0];
    await getMatData();
  });
}

function filterCate(data: ObjectProps[], cate: string) {
  if (cate === "全部") {
    return data;
  }
  return data.filter((item: ObjectProps) => item.type_name === cate);
}

// endregion

// region 组件事件的集合
const search = () => {
  getMatData();
};

const cateClick = (item: CategoryProp) => {
  categoryChoose.value = item;
  gridOption.dataSource = filterCate(cloneDeep(tableDataSource), item.name);
};

const delCate = () => {};
const addCate = () => {
  proxy.$auMessageBox.prompt("分类名称", "新增分类", {
    inputPlaceholder: "请输入新增的规格标题",
    inputValidator: (value: string) => {
      return !(!value || value?.trim() === "");
    },
    inputErrorMessage: "规格标题不能为空"
  });
};

type ActionType = {
  key: ACTION_TYPE;
  row: MaterialDetailProp;
};
const actionClick = ({ key, row }: ActionType) => {
  switch (key) {
    case ACTION_TYPE.EDIT:
      router.push({
        path: "/expiry/expiryDetail",
        query: {
          // id: row?.id,
          // materialId: row?.material_id
          row: JSON.stringify(row)
        }
      });
      break;
  }
};
// endregion

onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
.mat-btn {
  :deep(.btn_) {
    .el-form-item__content {
      justify-content: end;
    }
  }
}

.striped {
  &:nth-child(2n + 1) {
    background: var(--autata-striped-bg-color);
  }
}

.cate {
  width: 100%;
  height: 46px;
  padding-left: 20px;
  margin-right: 0;
  font-size: 14px;
  font-weight: 400;
  line-height: 46px;
  color: var(--autata-font-color);
  transition: all 0.3s;

  &.active {
    color: var(--el-color-primary);
    background: var(--autata-hover-bg-color);
  }

  &:hover {
    color: var(--el-color-primary);
    cursor: pointer;
    background: var(--autata-hover-bg-color);
  }
}

body .cate-left {
  :deep(.scroll-height) {
    height: calc(100vh - 260px);
  }
}
</style>
